package com.netty.code.self.resp.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * TODO
 * @author wuzz
 * @since 2024/7/11
 */
public class NioServer {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.bind(new InetSocketAddress(8888));

        Selector open = Selector.open();
        socketChannel.register(open, SelectionKey.OP_ACCEPT);


        while (true) {
            if (open.select(1000) == 0) {
                System.out.println("等待了1秒，无连接");
                continue;
            }
            // 有链接

            Set<SelectionKey> selectionKeys = open.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    // 为该客户端生成一个channel
                    SocketChannel accept = socketChannel.accept();
                    System.out.println("收到一个客户端，并设置为非阻塞，否则报错：IllegalBlockingModeException");
                    accept.configureBlocking(false);
                    // 接下来就关注读事件了
                    accept.register(open, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();

                    // 获取该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();

                    // 读取数据
                    channel.read(buffer);
                    System.out.println("from客户端：：：" + new String(buffer.array()));
                }
            }
        }
    }
}
